//
//  UIView+Common.m
//  ylb
//
//  Created by liz on 16/3/15.
//  Copyright © 2016年 gravel. All rights reserved.
//

#import "UIView+Common.h"
#define kTagBadgeView  1000
#define kTagBadgePointView  1001
#define kTagLineView 1007
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>
static const void *HttpRequestHUDKey = &HttpRequestHUDKey;
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

@implementation UIView(Common)
static char LoadingViewKey,LoadingBackViewKey, BlankPageViewKey;
@dynamic borderColor,borderWidth,cornerRadius, masksToBounds;

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
-(void)showInfica{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
-(void)hideInfica{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}








-(void)setBorderColor:(UIColor *)borderColor{
    [self.layer setBorderColor:borderColor.CGColor];
}

-(void)setBorderWidth:(CGFloat)borderWidth{
    [self.layer setBorderWidth:borderWidth];
}

-(void)setCornerRadius:(CGFloat)cornerRadius{
    [self.layer setCornerRadius:cornerRadius];
}

- (void)setMasksToBounds:(BOOL)masksToBounds{
    [self.layer setMasksToBounds:masksToBounds];
}





- (UIViewController *)findViewController
{
    for (UIView* next = self; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

- (void)addBadgePoint:(NSInteger)pointRadius withPosition:(BadgePositionType)type {
    
    if(pointRadius < 1)
        return;
    
    [self removeBadgePoint];
    
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = kTagBadgePointView;
    badgeView.layer.cornerRadius = pointRadius;
    badgeView.backgroundColor = [UIColor redColor];
    
    switch (type) {
            
        case BadgePositionTypeMiddle:
            badgeView.frame = CGRectMake(0, self.frame.size.height / 2 - pointRadius, 2 * pointRadius, 2 * pointRadius);
            break;
            
        default:
            badgeView.frame = CGRectMake(self.frame.size.width - 2 * pointRadius, 0, 2 * pointRadius, 2 * pointRadius);
            break;
    }
    
    [self addSubview:badgeView];
}




- (void)addLineUp:(BOOL)hasUp andDown:(BOOL)hasDown andColor:(UIColor *)color{
    [self removeViewWithTag:kTagLineView];
    if (hasUp) {
        UIView *upView = [UIView lineViewWithPointYY:0 andColor:color];
        upView.tag = kTagLineView;
        [self addSubview:upView];
    }
    if (hasDown) {
        UIView *downView = [UIView lineViewWithPointYY:CGRectGetMaxY(self.bounds)-0.5 andColor:color];
        downView.tag = kTagLineView;
        [self addSubview:downView];
    }
    return [self addLineUp:hasUp andDown:hasDown andColor:color andLeftSpace:0];
}
- (void)addLineUp:(BOOL)hasUp andDown:(BOOL)hasDown andColor:(UIColor *)color andLeftSpace:(CGFloat)leftSpace{
    [self removeViewWithTag:kTagLineView];
    if (hasUp) {
        UIView *upView = [UIView lineViewWithPointYY:0 andColor:color andLeftSpace:leftSpace];
        upView.tag = kTagLineView;
        [self addSubview:upView];
    }
    if (hasDown) {
        UIView *downView = [UIView lineViewWithPointYY:CGRectGetMaxY(self.bounds)-0.5 andColor:color andLeftSpace:leftSpace];
        downView.tag = kTagLineView;
        [self addSubview:downView];
    }
}
- (void)removeViewWithTag:(NSInteger)tag{
    for (UIView *aView in [self subviews]) {
        if (aView.tag == tag) {
            [aView removeFromSuperview];
        }
    }
}



+ (UIViewAnimationOptions)animationOptionsForCurve:(UIViewAnimationCurve)curve
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
            break;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
            break;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
            break;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
            break;
    }
    
    return kNilOptions;
}


+ (UIView *)lineViewWithPointYY:(CGFloat)pointY andColor:(UIColor *)color{
    return [self lineViewWithPointYY:pointY andColor:color andLeftSpace:0];
}



+ (void)outputTreeInView:(UIView *)view withSeparatorCount:(NSInteger)count{
    NSString *outputStr = @"";
    outputStr = [outputStr stringByReplacingCharactersInRange:NSMakeRange(0, count) withString:@"-"];
    outputStr = [outputStr stringByAppendingString:view.description];
    printf("%s\n", outputStr.UTF8String);
    
    if (view.subviews.count == 0) {
        return;
    }else{
        count++;
        for (UIView *subV in view.subviews) {
            [self outputTreeInView:subV withSeparatorCount:count];
        }
    }
}


#pragma mark LoadingView
- (void)setLoadingView:(LoadingView *)loadingView{
    [self willChangeValueForKey:@"LoadingViewKey"];
    objc_setAssociatedObject(self, &LoadingViewKey,
                             loadingView,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"LoadingViewKey"];
}
- (LoadingView *)loadingView{
    return objc_getAssociatedObject(self, &LoadingViewKey);
}
-(UIView*)loadingBackView{
    return objc_getAssociatedObject(self, &LoadingBackViewKey);
}
- (void)setLoadingBackView:(UIView *)loadingBackView{
    [self willChangeValueForKey:@"LoadingBackViewKey"];
    objc_setAssociatedObject(self, &LoadingBackViewKey,
                             loadingBackView,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"LoadingViewKey"];
}
-(void)beginLoadingWithBack{
    
    for (UIView *aView in [self.blankPageContainer subviews]) {
        if ([aView isKindOfClass:[BlankPageView class]] && !aView.hidden) {
            return;
        }
    }
    if (!self.loadingBackView) { //初始化LoadingView
        self.loadingBackView = [[UIView alloc] initWithFrame:self.bounds];
        self.loadingBackView.backgroundColor=[UIColor colorWithWhite:0.000 alpha:0.295];
    }
    
    self.loadingBackView.hidden=NO;
    [self addSubview:self.loadingBackView];
    [self.loadingBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.self.edges.equalTo(self);
    }];
    if (!self.loadingView) { //初始化LoadingView
        self.loadingView = [[LoadingView alloc] initWithFrame:self.bounds];
    }
    [self addSubview:self.loadingView];
    [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.self.edges.equalTo(self);
    }];
    [self.loadingView startAnimating];
}

- (void)beginLoading{
    for (UIView *aView in [self.blankPageContainer subviews]) {
        if ([aView isKindOfClass:[BlankPageView class]] && !aView.hidden) {
            return;
        }
    }
    
    if (!self.loadingView) { //初始化LoadingView
        self.loadingView = [[LoadingView alloc] initWithFrame:self.bounds];
    }
    [self addSubview:self.loadingView];
    [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.self.edges.equalTo(self);
    }];
    [self.loadingView startAnimating];
}

- (void)endLoading{
    if (self.loadingView) {
        [self.loadingView stopAnimating];
    }
    if(self.loadingBackView){
        self.loadingBackView.hidden=YES;
    }
}

#pragma mark BlankPageView
- (void)setBlankPageView:(BlankPageView *)blankPageView{
    [self willChangeValueForKey:@"BlankPageViewKey"];
    objc_setAssociatedObject(self, &BlankPageViewKey,
                             blankPageView,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"BlankPageViewKey"];
}

- (BlankPageView *)blankPageView{
    return objc_getAssociatedObject(self, &BlankPageViewKey);
}

- (void)configBlankPage:(EaseBlankPageType)blankPageType hasData:(BOOL)hasData hasError:(BOOL)hasError reloadButtonBlock:(void (^)(id))block{
    if (hasData) {
        if (self.blankPageView) {
            self.blankPageView.hidden = YES;
            [self.blankPageView removeFromSuperview];
        }
    }else{
        if (!self.blankPageView) {
            self.blankPageView = [[BlankPageView alloc] initWithFrame:self.bounds];
        }
        self.blankPageView.hidden = NO;
        [self.blankPageContainer addSubview:self.blankPageView];
        
        [self.blankPageView configWithType:blankPageType hasData:hasData hasError:hasError reloadButtonBlock:block];
    }
}
- (UIView *)blankPageContainer{
    UIView *blankPageContainer = self;
    for (UIView *aView in [self subviews]) {
        if ([aView isKindOfClass:[UITableView class]]) {
            blankPageContainer = aView;
        }
    }
    return blankPageContainer;
}

@end

@interface LoadingView ()
@property (nonatomic, assign) CGFloat loopAngle, monkeyAlpha, angleStep, alphaStep;
@end

@implementation LoadingView

- (instancetype)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];

        _loopView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading_loop"]];
        _monkeyView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading_logo"]];
        [_loopView setCenter:self.center];
        [_monkeyView setCenter:self.center];
        [self addSubview:_loopView];
        [self addSubview:_monkeyView];
        [_loopView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
        }];
        [_monkeyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
        }];
        
        _loopAngle = 0.0;
        _monkeyAlpha = 1.0;
        _angleStep = 360/3;
        _alphaStep = 1.0/3.0;
    }
    return self;
}

- (void)startAnimating{
    self.hidden = NO;
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    [self loadingAnimation];
}

- (void)stopAnimating{
    self.hidden = YES;
    _isLoading = NO;
}

- (void)loadingAnimation{
    static CGFloat duration = 0.25f;
    _loopAngle += _angleStep;
    if (_monkeyAlpha >= 1.0 || _monkeyAlpha <= 0.0) {
        _alphaStep = -_alphaStep;
    }
    _monkeyAlpha += _alphaStep;
    [UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        CGAffineTransform loopAngleTransform = CGAffineTransformMakeRotation(_loopAngle * (M_PI / 180.0f));
        _loopView.transform = loopAngleTransform;
        _monkeyView.alpha = _monkeyAlpha;
    } completion:^(BOOL finished) {
        if (_isLoading && [self superview] != nil) {
            [self loadingAnimation];
        }else{
            [self removeFromSuperview];
            
            _loopAngle = 0.0;
            _monkeyAlpha = 1,0;
            _alphaStep = ABS(_alphaStep);
            CGAffineTransform loopAngleTransform = CGAffineTransformMakeRotation(_loopAngle * (M_PI / 180.0f));
            _loopView.transform = loopAngleTransform;
            _monkeyView.alpha = _monkeyAlpha;
        }
    }];
}

@end

@implementation BlankPageView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)configWithType:(EaseBlankPageType)blankPageType hasData:(BOOL)hasData hasError:(BOOL)hasError reloadButtonBlock:(void (^)(id))block{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (_loadAndShowStatusBlock) {
            _loadAndShowStatusBlock();
        }
    });
    
    if (hasData) {
        [self removeFromSuperview];
        return;
    }
    self.alpha = 1.0;
    //    图片
    if (!_monkeyView) {
        _monkeyView = [[UIImageView alloc] init];
        [self addSubview:_monkeyView];
        [_monkeyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset([MyAdapter laDapter:77]);
            make.right.offset([MyAdapter laDapter:-77]);
            make.bottom.offset([MyAdapter laDapter:-224]);

        }];
    }
    //    文字
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _tipLabel.backgroundColor = [UIColor clearColor];
        _tipLabel.numberOfLines = 0;
        _tipLabel.font = [UIFont systemFontOfSize:15];
        _tipLabel.textColor = [UIColor lightGrayColor];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_tipLabel];
    }
    
    //    布局
    [_monkeyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.bottom.equalTo(self.mas_centerY);
    }];
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.top.equalTo(_monkeyView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    
    _reloadButtonBlock = nil;
    if (hasError) {
        //        加载失败
        if (!_reloadButton) {
            _reloadButton = [[UIButton alloc] initWithFrame:CGRectZero];
            [_reloadButton setImage:[UIImage imageNamed:@"blankpage_button_reload"] forState:UIControlStateNormal];
            _reloadButton.adjustsImageWhenHighlighted = YES;
            [_reloadButton addTarget:self action:@selector(reloadButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:_reloadButton];
            [_reloadButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self);
                make.top.equalTo(_tipLabel.mas_bottom);
                make.size.mas_equalTo(CGSizeMake(160, 60));
            }];
        }
        _reloadButton.hidden = NO;
        _reloadButtonBlock = block;
        [_monkeyView setImage:[UIImage imageNamed:@"blankpage_image_loadFail"]];
        _tipLabel.text = @"貌似出了点差错\n请重新尝试";
    }else{
        //        空白数据
        if (_reloadButton) {
            _reloadButton.hidden = YES;
        }
        NSString *imageName, *tipStr;
        _curType=blankPageType;
        switch (blankPageType) {
            case BlankPageBalanceDetail:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"您还没有余额详情哦~";
            }
                break;
                case BlankPageEvaluation:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"还没有评价哦~";
            }
                break;
            case BlankPageEva:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"还没有评价哦~";
            }
                break;
                case BlankPageFavorite:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"您还没有收藏哦~";
            }
                break;
            case BlankPageMyDesign:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"您还没有设计";
            }
                break;
            case BlankPageCoupon:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"您还没有优惠劵哦~";
            }
                break;
                case BlankPageShopCar:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"购物车没有商品哦~";
                
            }
                break;
            case BlankPageMessage1:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"您还没有消息哦!";
            }
                break;
            case BlankPageNOLogin:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"您还没有登录~";
            }
                break;
            case BlankPageReceiveAddress:{
                imageName = @"blankpage_image_address";
                tipStr = @"暂无收获地址";
            }
                break;
            case BlankPageActivity://
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"管理员很懒\n一条数据都没有";
            }
                break;
            case BlankPageTreat://
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"管理员很懒\n一篇规范诊疗都没有";
                break;
            }case BlankPageComment:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"还没有评论,快来添加评论吧";
                break;
            }case BlackPageOrderReport:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"该分类暂无药品,快试试其它分类吧";
                break;
            }case BlankPageMyOrder:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"您还没有订单哦";
                break;
            }case BlankPageMessage:
            {
                imageName=@"blankpage_image_Sleep";
                tipStr = @"您还没有消息哦";
                break;
            }case BlackPageFeedback:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"您还没有反馈哦！";
                break;
            }case BlackPageBounds:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"您还没有医米记录哦！";
                break;
            }case BlankPageCommdity:{
              //  imageName=@"blankpage_image_Sleep";
                tipStr = @"管理员很懒\n一个商品都没有！";
                break;
            }case BlankPageCommodity:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"此分类暂无商品，去其他分类看看吧！";
                break;
            }case BlankPageShop:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"暂无优惠券哦~";
                break;
            }case BlankPageCollection:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"您还没有收藏，去逛逛吧";
                break;
            }case BlankPageNOSearch:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"未搜到相关商品，更换关键词试试吧";
                break;
            }
            case BlankPageNOParameter:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"该商品没有相应产品参数";
                break;
            }
            case BlankPageNOMINGXI:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"暂无明细";
                break;
            }
            case BlankPageNOSY:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"您还没有推广收益";
                break;
            }
            case BlankPageNOAccount:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"您还没有提现账号，快去添加一个吧";
                break;
            }
            case BlankPageServiceQuery:{
                imageName=@"blankpage_image_Sleep";
                tipStr = @"该城市暂无开通服务商";
                break;
            }
            case BlankPageNOPosition:{
                imageName=@"blankpage_image_loadFail";
                tipStr = @"定位服务未开启，请进入系统「设置」--「隐私」--「定位服务」中打开开关，并允许谷子烘焙使用定位服务";
                break;
            }
            case BlankPageErrorPosition:
            {
                imageName = @"blankpage_image_loadFail";
                tipStr = @"获取位置信息失败，请稍后重试";
            }
                break;
            case BlankPageNOFAQ:
            {
                imageName = @"blankpage_image_Sleep";
                tipStr = @"暂无数据";
            }
                break;
            case BlankReleaseView:
            {
                imageName = @"elephant";
                tipStr  = @"";
            }
                break;
            default:
                break;
        }
        
        [_monkeyView setImage:[UIImage imageNamed:imageName]];
        _tipLabel.text = tipStr;
        
        if ((blankPageType>BlankPageType_NoButton)) {
            [_monkeyView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self);
                make.bottom.equalTo(self.mas_centerY).offset(-35);
            }];
            
            //新增按钮
//            AmotButton *actionBtn=({
//                AmotButton *button=[AmotButton new];
//                button.backgroundColor=COMMON_LIGHT_COLOR;
//                button.titleLabel.font=[UIFont systemFontOfSize:15];
//                [button addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
//                button.layer.cornerRadius=18;
//                button.layer.masksToBounds=TRUE;
//                button;
//            });
//            [self addSubview:actionBtn];
//
//            [actionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.size.mas_equalTo(CGSizeMake(125 , 36));
//                make.top.equalTo(_tipLabel.mas_bottom).offset(15);
//                make.centerX.equalTo(self);
//            }];
            
            NSString *titleStr;
            switch (blankPageType) {
                case BlankPageComment:
                    titleStr=@"+ 评论";
                    //                    [actionBtn setTitle:@"+ 创建项目" forState:UIControlStateNormal];
                    break;
                case BlankPageReceiveAddress:
                    titleStr = @"＋添加收货地址";
                    break;
                case BlankPageMessage1:
                    titleStr = @"刷新";
                    break;
                    
                default:
                    break;
            }
            //            NSMutableAttributedString *titleFontStr=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"+ %@",titleStr]];
            //            NSRange range;
            //            range.location=0;
            //            range.length=1;
            //            [titleFontStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range];
            //            [actionBtn setAttributedTitle:titleFontStr forState:UIControlStateNormal];
            
//            [actionBtn setTitle:titleStr forState:UIControlStateNormal];
            
        }
    }
}

- (void)reloadButtonClicked:(id)sender{
    self.hidden = YES;
    [self removeFromSuperview];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (_reloadButtonBlock) {
            _reloadButtonBlock(sender);
        }
    });
}

-(void)btnAction{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (_clickButtonBlock) {
            _clickButtonBlock(_curType);
        }
    });
}

@end
